package com.wenhuitec.android.tang.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.wenhuitec.android.tang.R;
import com.wenhuitec.android.tang.util.ScanKeyManager;
import com.wsm.hidlib.HIDManager;
import com.wsm.hidlib.callback.HIDDataListener;
import com.wsm.hidlib.callback.HIDOpenListener;
import com.wsm.hidlib.constant.ConnectCostant;
import com.wsm.hidlib.util.HexUtil;

public class ReadCardActivity extends AppCompatActivity {

    TextView text_Dialog;

    private Context mContext;

    private long lastCard;

    private ScanKeyManager scanKeyManager;

    public static void startAct(Context context) {
        Intent intent = new Intent(context, ReadCardActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_read_card);
        mContext = this;
        text_Dialog = findViewById(R.id.text_Dialog);
        text_Dialog.setText("请刷卡");
        findViewById(R.id.closeBtn).setOnClickListener(view -> {
            finish();
        });
        scanKeyManager = new ScanKeyManager((String value) -> {
            Log.i("ReadCardActivity", "ScanValue->" + value);
            getCardInfo(value);
        });
    }


    private int READ_OK = 1;
    private HIDOpenListener mHIDOpenListener;
    private HIDDataListener mHidDataListener;

    private void initHID() {
        HIDManager.getInstance().enableLog(true);
        HIDManager.getInstance().openHID(mContext, mHIDOpenListener, mHidDataListener);
    }

    private void initListener() {
        //回调数据有关页面展示的请在主线程进行。
        mHIDOpenListener = new HIDOpenListener() {
            @Override
            public void openSuccess(final int openSuccessStatus) {
                runOnUiThread(() -> {
                    if (openSuccessStatus == ConnectCostant.USB_CONNECT) {
                        System.out.println("连接USB");

                    } else if (openSuccessStatus == ConnectCostant.COMMUNICATION_OPEN) {
                        System.out.println("通讯建立");
                    }
                });
            }

            @Override
            public void openError(int openErrorStatus) {
                if (openErrorStatus == ConnectCostant.USB_DISCONNECT) {
                    //USB断开
                    System.out.println("断开USB");
                }
                if (openErrorStatus == ConnectCostant.COMMUNICATION_CLOSE) {
                    //服务销毁
                    System.out.println("通讯断开");
                }
            }
        };

        mHidDataListener = new HIDDataListener() {
            @Override
            public void onDataReceived(byte status, String dataMessage) {
                if (!TextUtils.isEmpty(dataMessage)) {
                    String result = dataMessage;
                    System.out.println("onDataReceived: length:" + dataMessage.length() + "   content:" + result);
                    Message message = Message.obtain();
                    message.what = READ_OK;
                    message.obj = result;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onOriginalDataReceived(byte status, byte[] bytes, int length) {
                String formatHexString = HexUtil.formatHexString(bytes);
                System.out.println("onOriginalDataReceived: " + formatHexString);
            }
        };
    }


    @Override
    protected void onResume() {
        super.onResume();
        initListener();
        initHID();
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == READ_OK) {
                String data = (String) msg.obj;
                data = data.trim();
                getCardInfo(data);
            }
        }
    };

    private void getCardInfo(String cardSn) {
        if (System.currentTimeMillis() - lastCard > (5 * 1000)) {
            lastCard = System.currentTimeMillis();
        } else {
            Toast.makeText(mContext, "请勿重复刷卡", Toast.LENGTH_LONG).show();
            return;
        }
        RequestUtils.getFk(mContext, cardSn, new MyObserverRes<JSONObject>(mContext) {
            @Override
            public void onSuccess(JSONObject result) {
                if (result == null) {
                    text_Dialog.setText("查无此人");
                    return;
                }
                System.out.println(result.toJSONString());
                String name = result.getString("name");
                String kye = result.getString("kye");
                String btye = result.getString("btye");
                text_Dialog.setText(String.format("姓名：%s\r\n 卡余额:%s\r\n卡补贴余额：%s", name, kye, btye));
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                Log.e("ReadCardActivity", errorMsg, e);
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        HIDManager.getInstance().closeHID();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            scanKeyManager.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}
